﻿using System;
using System.Linq;
using Wintellect.Sterling;
using Wintellect.Sterling.Database;
using Caramel.Entities;

namespace Caramel.Sterling.Entities
{
	public class IdentityTrigger<T> : BaseSterlingTrigger<T, int?> where T : class, IEntity<int?>, new()
	{
		public IdentityTrigger(ISterlingDatabaseInstance databaseInstance)
		{
			// if a record exists, set it to the highest value plus 1
			if (databaseInstance.Query<T, int?>().Any())
			{
				CurrentIndex = 
					databaseInstance.Query<T, int>().
						Max(key => key.Key) + 1;
			}
		}

		protected static int CurrentIndex { get; set; }

		public override bool BeforeSave(T instance)
		{
			if (instance.ID == null)
			{
				// HACK!!!
				typeof(Entity<int?>).
					GetProperty("ID").
					SetValue(instance, CurrentIndex++, null);
			}

			return true;
		}

		public override void AfterSave(T instance)
		{
			return;
		}

		public override bool BeforeDelete(int? key)
		{
			return true;
		}
	}

}
